package com.service.scheduling.framework.config;

import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.data.redis.RedisProperties;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisStandaloneConfiguration;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.connection.lettuce.LettucePoolingClientConfiguration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import java.time.Duration;

/** 
 *
 *  @desc
 */

@Configuration
//@EnableCaching
public class RedisConfig extends CachingConfigurerSupport {

    /**
     * 基础配置
     * @param redisConnectionFactory
     * @return
     */
    @Bean("redisTemplate")
    public RedisTemplate<String, String> redisTemplate(@Qualifier("redisConnectionFactory") @Autowired LettuceConnectionFactory redisConnectionFactory) {
        RedisTemplate<String, String> redisTemplate = new RedisTemplate<String, String>();
        redisTemplate.setConnectionFactory(redisConnectionFactory);

        //使用StringRedisSerializer来序列化和反序列化redis的key
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setValueSerializer(new StringRedisSerializer());

        //使用Jackson2JsonRedisSerializer来序列化和反序列化redis的value值
        redisTemplate.setHashKeySerializer(new StringRedisSerializer());
        redisTemplate.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());


        //开启事务
//        redisTemplate.setEnableTransactionSupport(true);
        redisTemplate.afterPropertiesSet();
        return redisTemplate;
    }

    @Bean
    @Override
    public KeyGenerator keyGenerator() {
        return (target, method, objects) -> {
            StringBuilder sb = new StringBuilder();
            sb.append(target.getClass().getName());
            sb.append("::" + method.getName() + ":");
            for (Object obj : objects) {
                sb.append(obj.toString());
            }
            return sb.toString();
        };
    }

    @Bean
    public CacheManager cacheManager(@Qualifier("redisConnectionFactory") @Autowired LettuceConnectionFactory redisConnectionFactory) {
        RedisCacheManager redisCacheManager = RedisCacheManager.builder(redisConnectionFactory).build();
        //设置缓存过期时间
//        redisCacheManager.setDefaultExpiration(10000);
        return redisCacheManager;
    }

    @Configuration
    public static class RedisConf {
        @Value("${spring.redis.lettuce.pool.min-idle}")
        private int minIdle;
        @Value("${spring.redis.lettuce.pool.max-idle}")
        private int maxIdle;
        @Value("${spring.redis.lettuce.pool.max-active}")
        private int maxActive;
        @Value("${spring.redis.lettuce.pool.max-wait}")
        private Duration maxWait;

        @Value("${spring.redis.host}")
        private String host;
        @Value("${spring.redis.port}")
        private int port;
        @Value("${spring.redis.timeout}")
        private Duration timeout;
        @Value("${spring.redis.database}")
        private int database;
        @Value("${spring.redis.password}")
        private String password;


        /**
         * 获取缓存连接池
         *
         * @return
         */
        @Bean
        public LettucePoolingClientConfiguration lettucePoolingClientConfiguration(RedisProperties redisProperties) {

            GenericObjectPoolConfig pool = new GenericObjectPoolConfig();
            pool.setMaxTotal(maxActive);
            pool.setMaxWaitMillis(maxWait.toMillis());
            pool.setMaxIdle(maxIdle);
            pool.setMinIdle(minIdle);
            LettucePoolingClientConfiguration lettucePoolingClientConfiguration = LettucePoolingClientConfiguration.builder()
                    .poolConfig(pool)
                    .commandTimeout(timeout)
                    .shutdownTimeout(timeout)
                    .build();
            return lettucePoolingClientConfiguration;
        }

        @Bean
        public RedisStandaloneConfiguration redisStandaloneConfiguration(RedisProperties redisProperties) {
            RedisStandaloneConfiguration config = new RedisStandaloneConfiguration();
            config.setHostName(host);
            config.setPort(port);
            config.setDatabase(database);
            config.setPassword(password);
            return config;
        }

        /**
         * jedis连接工厂
         * @return
         */
        @Bean
        public LettuceConnectionFactory redisConnectionFactory(@Qualifier("redisStandaloneConfiguration") @Autowired RedisStandaloneConfiguration redisStandaloneConfiguration,
                                                                  @Qualifier("lettucePoolingClientConfiguration") @Autowired LettucePoolingClientConfiguration lettucePoolingClientConfiguration) {
            LettuceConnectionFactory redisConnectionFactory = new LettuceConnectionFactory(redisStandaloneConfiguration, lettucePoolingClientConfiguration);
            redisConnectionFactory.setShareNativeConnection(false);
            return redisConnectionFactory;
        }
    }

}